package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.model.domain.Analysis;
import com.tanhua.model.domain.Year;
import com.tanhua.model.vo.AnalysisSummaryVo;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PanelService {
    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 查询首页头部基本信息
     *
     * @return
     */
    public AnalysisSummaryVo findSummary() {

        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();

        Date now = Calendar.getInstance().getTime();

        //累计用户数
        Integer total = analysisService.queryCumulativeUsers();
        analysisSummaryVo.setCumulativeUsers(Long.valueOf(total));

        //查询今日统计信息
        Analysis today_analysis = analysisService.querySummary(now);

        //过去30天活跃用户
        analysisSummaryVo.setActivePassMonth(Long.valueOf(today_analysis.getNumActive30()));

        //过去7天活跃用户
        analysisSummaryVo.setActivePassWeek(Long.valueOf(today_analysis.getNumActive7()));

        //今日活跃用户
        analysisSummaryVo.setActiveUsersToday(Long.valueOf(today_analysis.getNumActive()));

        //今日新增用户
        analysisSummaryVo.setNewUsersToday(Long.valueOf(today_analysis.getNumRegistered()));

        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        //查询昨日统计信息
        Analysis yes_analysis = analysisService.querySummary(DateUtils.addDays(now, -1));

        analysisSummaryVo.setNewUsersTodayRate(computeRate(Long.valueOf(today_analysis.getNumRegistered()), Long.valueOf(yes_analysis.getNumRegistered())));

        //今日登录次数
        analysisSummaryVo.setLoginTimesToday(Long.valueOf(today_analysis.getNumLogin()));

        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        analysisSummaryVo.setLoginTimesTodayRate(computeRate(Long.valueOf(today_analysis.getNumLogin()), Long.valueOf(yes_analysis.getNumLogin())));

        //活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        analysisSummaryVo.setActiveUsersTodayRate(computeRate(Long.valueOf(today_analysis.getNumActive()), Long.valueOf(yes_analysis.getNumActive())));

        return analysisSummaryVo;
    }

    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }

    private static String offsetDay(Date date, int offSet) {
        return DateUtil.offsetDay(date, offSet).toDateStr();

    }


    /**
     * 可视化
     */
    public Map findByUsers(String sd, String ed, String type) {
       /* long time = Long.parseLong(ed) - Long.parseLong(sd);
        time = time / 86400000;
        int day = time.intValue();
        System.err.println(day);*/

        //查询规定时间内所有的统计数据集合
        LambdaQueryWrapper<Analysis> lwq = new LambdaQueryWrapper<>();
        lwq.le(Analysis::getRecordDate, new Date(Long.parseLong(ed))).ge(Analysis::getRecordDate, new Date(Long.parseLong(sd)));
        List<Analysis> analyses = analysisMapper.selectList(lwq);
        //构造返回对象
        Map map = new HashMap();
        List<Year> list = new ArrayList<>();
        //构造vo
        for (Analysis analysis : analyses) {
            Year year = new Year();
            year.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));

            //根据类型查询需要不同的数据
            if ("101".equals(type)) {
                year.setAmount(analysis.getNumRegistered());
            } else if ("102".equals(type)) {
                year.setAmount(analysis.getNumActive());
            } else if ("103".equals(type)) {
                year.setAmount(analysis.getNumRetention1d());
            }
            list.add(year);
        }
        //添加今年的数据到map集合
        map.put("thisYear", list);

        //查询去年的数据
        //获取去年的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(Long.parseLong(ed)));
        //获取去年的日期 当前时间减去一年得到去年的日期
        calendar.add(Calendar.YEAR, -1);
        //去年结束日期
        Date endTime = calendar.getTime();

        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new Date(Long.parseLong(sd)));
        //当前时间减去一年
        calendar1.add(Calendar.YEAR,-1);
        //去年开始日期
        Date startTime = calendar1.getTime();

        //查询去年数据
        LambdaQueryWrapper<Analysis> lwq1 = new LambdaQueryWrapper<>();
        lwq1.le(Analysis::getRecordDate,endTime).ge(Analysis::getRecordDate,startTime);
        List<Analysis> analyses1 = analysisMapper.selectList(lwq1);
        List<Year> list1=new ArrayList<>();
        for (Analysis analysis : analyses1) {
            Year year = new Year();
            year.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
            if ("101".equals(type)){
                year.setAmount(analysis.getNumRegistered());
            }else if ("102".equals(type)){
                year.setAmount(analysis.getNumActive());
            }else if ("103".equals(analysis.getNumRetention1d()));
            list1.add(year);
        }
        //添加去年的数据到map集合
        map.put("lastYear",list1);
        return map;
    }
}
